#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include "cJSON/cJSON.h"
#include "cgic.h"


int cgiMain()
{
    // FILE *file = fopen("/www/cjson_dir/network_detail.json", "r");
    FILE *file = fopen("/demo/bin/boa/www/cjson_dir/network_detail.json", "r");
    if (file == NULL)
    {
        perror("打开文件时出错");
        return EXIT_FAILURE;
    }
    fseek(file, 0, SEEK_END);
    long length = ftell(file);
    fseek(file, 0, SEEK_SET);
    char *data = (char *)malloc(length + 1);
    fread(data, 1, length, file);
    data[length] = '\0';
    cJSON *json = cJSON_Parse(data);
    if (json == NULL)
    {
        printf("json parse error....\n");
    }

    cgiHeaderContentType("text/html");
    fprintf(cgiOut, "<HTML><HEAD>\n");
    fprintf(cgiOut, "<TITLE>Button</TITLE></HEAD>\n");
    fprintf(cgiOut, "<BODY>");

    cJSON *url_address_json = cJSON_GetObjectItem(json, "url_address");
    if(url_address_json != NULL)
    {
        char * url_address = url_address_json->valuestring;
        fprintf(cgiOut, "<H1>Now url_address is %s</H1>", url_address);
    }
    else
    {
        fprintf(cgiOut, "<H1>Now url_address is NULL</H1>");
    }

    fprintf(cgiOut, "<button type='button' onclick=window.location.href='/cgi-bin/start_fifo_cgi.cgi'>Start</button>\n");
    fprintf(cgiOut, "<button type='button' onclick=window.location.href='/cgi-bin/stop_fifo_cgi.cgi'>Stop</button>\n");
    fprintf(cgiOut, "<button type='button' onclick=window.location.href='../index_stream_detail.html'>Config Stream Detail</button>\n");

    fprintf(cgiOut, "</BODY>\n");
    fprintf(cgiOut, "</HTML>\n");

    return 0;
}